<template>
	<view class="container">
		<view class="content-wrapper">
			<!-- 基本信息 -->
			<view class="merchant-management">
				<view class="display-flex-start merchant-column">
					<view class="red-line"></view>
					<view class="merchant-info-name">商户基本信息</view>
				</view>
				<view class="display-flex-start item-info bottom-one-line">
					<view class="display-flex-start item-left">
						<view class="item-start">*</view>
						<view class="left-text">商户名称</view>
					</view>
					<view class="item-right">
						<up-input v-model="parameter.name" placeholder="请输入商户名称" border="none"></up-input>
					</view>
				</view>
				<view class="display-flex-start item-info bottom-one-line">
					<view class="display-flex-start item-left">
						<view class="item-start">*</view>
						<view class="left-text">行业类别</view>
					</view>
					<view class="item-right" @click="showIndustry = true">
						<view class="display-flex-space-between">
							<view class="rigit-text">{{ parameter.industryCategory }}</view>
							<image :src="getImagePath('/logo.png')" mode="widthFix" class="arrow-icon"></image>
						</view>
						<up-picker :show="showIndustry" :columns="industryData" @confirm="industryConfirm"
							@cancel="showIndustry = false"></up-picker>
					</view>
				</view>
				<view class="display-flex-start item-info bottom-one-line">
					<view class="display-flex-start item-left">
						<view class="item-start">*</view>
						<view class="left-text">经营地区</view>
					</view>
					<view class="item-right" @click="showArea = true">
						<view class="display-flex-space-between">
							<view class="rigit-text">{{ areaTitle }}</view>
							<image :src="getImagePath('/logo.png')" mode="widthFix" class="arrow-icon"></image>
						</view>
						<up-cascader v-model:show="showArea" v-model="area" :data="areaData" value-key="code"
							label-key="name" children-key="children" @confirm="areaConfirm"></up-cascader>
					</view>
				</view>
				<view class="display-flex-start item-info bottom-one-line">
					<view class="display-flex-start item-left">
						<view class="item-start">*</view>
						<view class="left-text">详细地址</view>
					</view>
					<view class="item-right">
						<up-input v-model="parameter.address" placeholder="请输入详细地址" border="none"></up-input>
					</view>
				</view>
				<view class="display-flex-start item-info bottom-one-line">
					<view class="display-flex-start item-left">
						<view class="item-start">*</view>
						<view class="left-text">地图位置</view>
					</view>
					<view class="item-right display-flex-end">
						<view class="select-postion" @click="openPostion()">选择定位</view>
					</view>
				</view>
				<view class="item-info bottom-one-line">
					<view class="display-flex-start ">
						<view class="item-start">*</view>
						<view class="left-text">经营地门店logo</view>
					</view>
					<view class="upload-management">
						<up-upload :fileList="logonList" @afterRead="(event) => afterRead(event, 'logoImage')"
							@delete="(event) => deletePic(event, 'logoImage')" name="1" multiple
							:maxCount="1"></up-upload>
					</view>
				</view>
				<view class="display-flex-start item-info bottom-one-line">
					<view class="display-flex-start item-left">
						<view class="item-start">*</view>
						<view class="left-text">营业开始时间</view>
					</view>
					<view class="item-right" @click="showStartTime = true">
						<view class="display-flex-space-between">
							<view class="rigit-text">{{ parameter.startTime }}</view>
							<image :src="getImagePath('/logo.png')" mode="widthFix" class="arrow-icon"></image>
						</view>
						<up-datetime-picker :show="showStartTime" mode="time" @confirm="startTimeConfirm"
							@cancel="showStartTime = false"></up-datetime-picker>
					</view>
				</view>
				<view class="display-flex-start item-info bottom-one-line">
					<view class="display-flex-start item-left">
						<view class="item-start">*</view>
						<view class="left-text">营业结束时间</view>
					</view>
					<view class="item-right" @click="showEndTime = true">
						<view class="display-flex-space-between">
							<view class="rigit-text">{{ parameter.endTime }}</view>
							<image :src="getImagePath('/logo.png')" mode="widthFix" class="arrow-icon"></image>
						</view>
						<up-datetime-picker :show="showEndTime" mode="time" @confirm="endTimeConfirm"
							@cancel="showEndTime = false"></up-datetime-picker>
					</view>
				</view>
				<view class="display-flex-start item-info bottom-one-line">
					<view class="display-flex-start item-left">
						<view class="item-start">*</view>
						<view class="left-text">让利比例</view>
					</view>
					<view class="item-right">
						<up-input v-model="parameter.discountRatio" placeholder="请输入让利比例" border="none"></up-input>
					</view>
				</view>
				<view class="item-info bottom-one-line">
					<view class="display-flex-start ">
						<view class="item-start">*</view>
						<view class="left-text">门店介绍图</view>
					</view>
					<view class="upload-management">
						<up-upload :fileList="introductionList" @afterRead="(event) => afterRead(event, 'descImage')"
							@delete="(event) => deletePic(event, 'descImage')" name="1" multiple
							:maxCount="3"></up-upload>
					</view>
				</view>
				<view class="item-info">
					<view class="display-flex-start ">
						<view class="left-text">简介特色</view>
					</view>
					<view class="upload-management">
						<up-textarea v-model="parameter.description" placeholder="请输入内容" count
							:maxlength="200"></up-textarea>
					</view>
				</view>
			</view>

			<!-- 认证信息 -->
			<view class="merchant-management">
				<view class="display-flex-start merchant-column">
					<view class="red-line"></view>
					<view class="merchant-info-name">商户认证信息</view>
				</view>
				<view class="display-flex-start item-info bottom-one-line">
					<view class="display-flex-start item-left">
						<view class="item-start">*</view>
						<view class="left-text">营业执照号</view>
					</view>
					<view class="item-right">
						<up-input v-model="parameter.licenceCode" placeholder="请输入营业执照号" border="none"></up-input>
					</view>
				</view>
				<view class="item-info bottom-one-line">
					<view class="display-flex-start ">
						<view class="item-start">*</view>
						<view class="left-text">营业执照</view>
					</view>
					<view class="upload-management">
						<up-upload :fileList="businessLicenseList"
							@afterRead="(event) => afterRead(event, 'licenceImage')"
							@delete="(event) => deletePic(event, 'licenceImage')" name="1" multiple
							:maxCount="1"></up-upload>
					</view>
				</view>
				<view class="display-flex-start item-info bottom-one-line">
					<view class="display-flex-start item-left">
						<view class="item-start">*</view>
						<view class="left-text">法人姓名</view>
					</view>
					<view class="item-right">
						<up-input v-model="parameter.legalName" placeholder="请输入法人姓名" border="none"></up-input>
					</view>
				</view>
				<view class="display-flex-start item-info bottom-one-line">
					<view class="display-flex-start item-left">
						<view class="item-start">*</view>
						<view class="left-text">法人身份证号</view>
					</view>
					<view class="item-right">
						<up-input v-model="parameter.legalNum" placeholder="请输入法人身份证号" border="none"></up-input>
					</view>
				</view>
				<view class="item-info bottom-one-line">
					<view class="display-flex-start ">
						<view class="item-start">*</view>
						<view class="left-text">法人身份证照</view>
					</view>
					<view class="upload-management">
						<view class="flex-space-around">
							<view class="upload-item">
								<up-upload :fileList="identityCardFront"
									@afterRead="(event) => afterRead(event, 'legalFrontImage')"
									@delete="(event) => deletePic(event, 'legalFrontImage')" name="1"
									:maxCount="1"></up-upload>

								<view class="upload-des">上传法人身份证人像面</view>
							</view>
							<view class="upload-item">
								<up-upload :fileList="identityCardReverseSide"
									@afterRead="(event) => afterRead(event, 'legalBackImage')"
									@delete="(event) => deletePic(event, 'legalBackImage')" name="1"
									:maxCount="1"></up-upload>
								<view class="upload-des">上传法人身份证国徽像面</view>
							</view>
						</view>
					</view>
				</view>
				<view class="display-flex-start item-info bottom-one-line">
					<view class="display-flex-start item-left">
						<view class="item-start">*</view>
						<view class="left-text">联系人电话</view>
					</view>
					<view class="item-right">
						<up-input v-model="parameter.legalTel" placeholder="请输入联系人电话" border="none"
							maxlength="11"></up-input>
					</view>
				</view>
			</view>

			<!-- 财务信息 -->
			<view class="merchant-management">
				<view class="display-flex-start merchant-column">
					<view class="red-line"></view>
					<view class="merchant-info-name">商户财务信息</view>
				</view>
				<view class="display-flex-start item-info bottom-one-line">
					<view class="display-flex-start item-left">
						<view class="item-start">*</view>
						<view class="left-text">开户银行名称</view>
					</view>
					<view class="item-right">
						<up-input v-model="parameter.bankName" placeholder="请输入开户银行名称" border="none"></up-input>
					</view>
				</view>
				<view class="display-flex-start item-info bottom-one-line">
					<view class="display-flex-start item-left">
						<view class="item-start">*</view>
						<view class="left-text">开户支行名称</view>
					</view>
					<view class="item-right">
						<up-input v-model="parameter.branchName" placeholder="请输入开户支行名称" border="none"
							maxlength="11"></up-input>
					</view>
				</view>
				<view class="display-flex-start item-info bottom-one-line">
					<view class="display-flex-start item-left">
						<view class="item-start">*</view>
						<view class="left-text">结算账户类型</view>
					</view>
					<view class="item-right">
						<up-radio-group v-model="parameter.settlementType" placement="row">
							<up-radio :customStyle="{ marginBottom: '8px' }" v-for="(item, index) in accountList"
								:key="index" :label="item.name" :name="item.id">
							</up-radio>
						</up-radio-group>
					</view>
				</view>
				<view class="display-flex-start item-info bottom-one-line">
					<view class="display-flex-start item-left">
						<view class="item-start">*</view>
						<view class="left-text">银行账号</view>
					</view>
					<view class="item-right">
						<up-input v-model="parameter.accountNum" placeholder="请输入银行账号" border="none"
							maxlength="11"></up-input>
					</view>
				</view>
				<view class="display-flex-start item-info">
					<view class="display-flex-start item-left">
						<view class="item-start">*</view>
						<view class="left-text">账户开户名</view>
					</view>
					<view class="item-right">
						<up-input v-model="parameter.accountName" placeholder="请输入账户开户名" border="none"
							maxlength="11"></up-input>
					</view>
				</view>
			</view>
			<view class="submit" @click="addMerchant()">提交</view>
		</view>
	</view>
</template>

<script>
	import {
		queryIndustryCategories,
		businessId,
		upload,
		delFile,
		merchantAdd,
		querySettlementType
	} from '@/common/index.js'
	import areaJson from '@/common/pca-code.json'
	import {
		getAreaNamesByCodes
	} from '@/common/area.js'
	import {
		stringIsNull,
		toast,
		validateIdCard,
		validateLicenseNo,
		validatePhone,
		validateNumber
	} from '@/common/common.js'
	export default {
		data() {
			return {
				//基本信息
				parameter: {
					id: null,
					recommendedCode: '', //推荐码
					discountRatio: null, //让利比例
					code: '123465', //商家编码
					bussinessId: '',
					moduleId: 'taskManager',
					name: '',
					industryCategory: '请选择行业类别',
					province: '',
					city: '',
					county: '',
					address: '',
					lng: null, //经度
					lat: null, //纬度
					logoImage: '',
					startTime: '请选择时间',
					endTime: '请选择时间',
					descImage: '',
					description: '',
					licenceCode: '',
					licenceImage: '',
					legalName: '',
					legalNum: '',
					legalFrontImage: '',
					legalBackImage: '',
					legalTel: '',
					bankName: '',
					branchName: '',
					settlementType: 0, //结算类型：0对公；1个人
					accountNum: '',
					accountName: '',
					status: 1, //是否有效（1 有效 0 无效）
				},
				showIndustry: false,
				industryData: [],
				showArea: false,
				areaTitle: '请选择经营地区类别',
				area: null,
				areaData: [],
				logonList: [],
				showStartTime: false,
				showEndTime: false,
				introductionList: [],
				//认证信息
				businessLicenseList: [],
				identityCardFront: [],
				identityCardReverseSide: [],
				//财务信息
				accountList: [],
			}
		},
		onLoad() {
			uni.setStorageSync('token', '46a49fe9bfb64a0c8b77986590cd17ab');
			this.getIndustryCategories();
			this.getBusinessId()
			this.getSettlementType()
			this.areaData = areaJson
		},
		beforeDestroy() {
			console.log('移除')
			uni.$off();
		},
		onShow() {
			let _this = this;
			uni.$once('commitCheck', (data) => {
				const [longitude, latitude] = data.location.split(',');
				const lng = parseFloat(longitude);
				const lat = parseFloat(latitude);
				_this.parameter.lat = latitude
				_this.parameter.lng = longitude
			});
		},
		methods: {
			//查询商家行业类别
			getIndustryCategories() {
				var reqdata = {
					data: {
						dmid: 'INDUSTRY_CATEGORY'
					}
				}
				queryIndustryCategories(reqdata).then(res => {
					if (res.code == 200) {
						let list = res.data.map(item => item.dmname);
						this.industryData = [list];
					} else {
						toast(res.msg)
					}
				})
			},
			//查询结算账户类型
			getSettlementType() {
				var reqdata = {
					data: {}
				}
				querySettlementType(reqdata).then(res => {
					if (res.code == 200) {
						this.accountList = res.data
					} else {
						toast(res.msg)
					}
				})
			},

			//行业
			industryConfirm(e) {
				this.parameter.industryCategory = e.value.toString();
				this.showIndustry = false
			},
			//地区
			areaConfirm(e) {
				let areaDic = getAreaNamesByCodes(e, areaJson)
				this.areaTitle = areaDic.province + areaDic.city + areaDic.district
				this.parameter.province = areaDic.province
				this.parameter.city = areaDic.city
				this.parameter.county = areaDic.district
				this.showArea = false
			},
			/// 获取定位
			openPostion() {
				console.log(1111);
				uni.navigateTo({
					url: '/pages/map/index'
				})
			},
			//营业开始时间
			startTimeConfirm(e) {
				this.parameter.startTime = e.value
				this.showStartTime = false
				this.validateTimeRange()
			},
			//营业结束时间
			endTimeConfirm(e) {
				this.parameter.endTime = e.value
				this.showEndTime = false
				this.validateTimeRange()
			},
			// 验证时间范围
			validateTimeRange() {
				// 确保两个时间都已设置
				if (!this.parameter.startTime || !this.parameter.endTime) return;

				// 将时间转换为分钟数进行比较
				const startMinutes = this.timeToMinutes(this.parameter.startTime);
				const endMinutes = this.timeToMinutes(this.parameter.endTime);

				// 检查结束时间是否小于或等于开始时间
				if (endMinutes <= startMinutes) {
					// 可以根据需要修改提示方式
					toast('结束时间不能早于或等于开始时间')
					// 清空无效的结束时间或重置为默认值
					this.parameter.endTime = '';
				}
			},

			// 将时间字符串转换为分钟数
			timeToMinutes(timeStr) {
				const [hours, minutes] = timeStr.split(':').map(Number);
				return hours * 60 + minutes;
			},
			// 新增图片 - 修改为 async 函数
			afterRead: async function(event, type) {
				// 定义类型与数据列表的映射关系
				const listMap = {
					logoImage: 'logonList', // 经营地门店logo
					descImage: 'introductionList', // 门店介绍图
					licenceImage: 'businessLicenseList', // 营业执照
					legalFrontImage: 'identityCardFront', // 法人身份证人像面
					legalBackImage: 'identityCardReverseSide' // 法人身份证国徽像面
				};
				// 验证类型是否有效
				if (!listMap[type]) {
					console.error('无效的图片类型:', type);
					return false;
				}
				// 获取当前类型对应的数据列表
				const currentListName = listMap[type];
				let currentList = this[currentListName];
				// 验证列表是否存在
				if (!Array.isArray(currentList)) {
					console.error(`数据列表${currentListName}不存在或不是数组`);
					return false;
				}
				// 处理文件列表
				const files = [].concat(event.file);
				const initialListLength = currentList.length;
				// 先将所有文件标记为上传中状态
				files.forEach(file => {
					currentList.push({
						...file,
						status: 'uploading',
						message: '上传中',
					});
				});
				// 逐个上传文件
				for (const [index, file] of files.entries()) {
					try {
						// 调用上传接口
						const result = await this.uploadFilePromise(file.url);
						// 更新上传成功状态
						currentList[initialListLength + index] = {
							...currentList[initialListLength + index],
							status: 'success',
							message: '',
							url: result,
						};
					} catch (error) {
						// 处理上传失败情况
						currentList[initialListLength + index] = {
							...currentList[initialListLength + index],
							status: 'error',
							message: '上传失败',
						};
						console.error(`文件${file.name}上传失败:`, error);
					}
				}
				// 更新实例中的列表数据
				this[currentListName] = currentList;
			},
			// 生成业务ID
			getBusinessId() {
				var reqdata = {
					data: {}
				}
				businessId(reqdata).then(res => {
					if (res.code == 200) {
						this.parameter.bussinessId = res.data
					} else {
						toast(res.msg)
					}
				})
			},

			// 上传
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: `https://lskj.lskejisoft.com/shujun/bizunion-server/pFile/upload`,
						filePath: url,
						name: 'files',
						formData: {
							bussinessId: this.parameter.bussinessId,
							moduleId: this.parameter.moduleId
						},
						header: {
							'Authorization': uni.getStorageSync('token')
						},
						success: (res) => {
							if (res.statusCode === 200) {
								// 建议先解析JSON（如果返回的是JSON格式）
								const result = JSON.parse(res.data);
								resolve(result.data);
							} else {
								reject(new Error(`上传失败，状态码: ${res.statusCode}`));
							}
						},
						fail: (err) => {
							reject(err);
						}
					});
				});
			},
			// 删除图片
			deletePic(event, type) {
				console.log('删除信息:', JSON.stringify(event), '类型:', type);
				// 定义类型与数据列表的映射关系（与afterRead保持一致）
				const listMap = {
					logoImage: 'logonList', // 经营地门店logo
					descImage: 'introductionList', // 门店介绍图
					licenceImage: 'businessLicenseList', // 营业执照
					legalFrontImage: 'identityCardFront', // 法人身份证人像面
					legalBackImage: 'identityCardReverseSide' // 法人身份证国徽像面
				};
				// 验证类型是否有效
				if (!listMap[type]) {
					console.error('无效的图片类型:', type);
					return false;
				}
				// 获取当前类型对应的数据列表
				const currentListName = listMap[type];
				let currentList = this[currentListName];
				// 验证列表是否存在且为数组
				if (!Array.isArray(currentList)) {
					console.error(`数据列表${currentListName}不存在或不是数组`);
					return false;
				}
				// 验证索引是否有效
				if (event.index === undefined || event.index < 0 || event.index >= currentList.length) {
					console.error('无效的索引值:', event.index);
					return false;
				}
				// 从列表中删除指定索引的图片
				currentList.splice(event.index, 1);
				// 更新实例中的列表数据（某些框架可能需要显式触发更新）
				this[currentListName] = [...currentList];
				this.goDelFile(event.file.url[0].id)
				return true;
			},
			//删除文件
			goDelFile(fileid) {
				var reqdata = {
					data: {
						fileId: fileid
					}
				}
				delFile(reqdata).then(res => {
					if (res.code == 200) {
						console.log('删除成功');
					} else {
						toast(res.msg)
					}
				})
			},
			//新增商户
			addMerchant() {
				console.log(JSON.stringify(this.introductionList))
				if (stringIsNull(this.parameter.name)) return toast('请输入商户名称')
				if (stringIsNull(this.parameter.industryCategory) ||
					this.parameter.industryCategory == '请选择行业类别')
					return toast('请选择行业类别')
				if (stringIsNull(this.parameter.province) ||
					stringIsNull(this.parameter.city) ||
					stringIsNull(this.parameter.county))
					return toast('请选择经营地区')
				if (stringIsNull(this.parameter.address)) return toast('请输入详细地址')
				if (stringIsNull(this.parameter.lat) || stringIsNull(this.parameter.lng))
					return toast('请选择位置')
				if (stringIsNull(this.logonList)) return toast('请上传门店logo')
				if (stringIsNull(this.parameter.startTime) ||
					this.parameter.startTime == '请选择时间') return toast('请选择营业开始时间')
				if (stringIsNull(this.parameter.endTime) ||
					this.parameter.endTime == '请选择时间') return toast('请选择营业结束时间')
				if (!validateNumber(this.parameter.discountRatio).valid) return toast('让利比例' + validateNumber(this
						.parameter
						.discountRatio)
					.message)
				if (stringIsNull(this.introductionList)) return toast('请上传门店介绍图')
				if (!validateLicenseNo(this.parameter.licenceCode).valid) return toast(validateLicenseNo(this.parameter
						.licenceCode)
					.message)
				if (stringIsNull(this.businessLicenseList)) return toast('请上传营业执照')
				if (stringIsNull(this.parameter.legalName)) return toast('请输入法人名称')
				if (!validateIdCard(this.parameter.legalNum).valid) return toast(validateIdCard(this.parameter.legalNum)
					.message)
				if (stringIsNull(this.identityCardFront)) return toast('请上传法人身份证人像面')
				if (stringIsNull(this.identityCardReverseSide)) return toast('请上传法人身份证国徽像面')
				if (!validatePhone(this.parameter.legalTel).valid) return toast(validatePhone(this.parameter.legalNum)
					.message)
				if (stringIsNull(this.parameter.bankName)) return toast('请输入开户银行名称')
				if (stringIsNull(this.parameter.branchName)) return toast('请输入开户支行名称')
				if (stringIsNull(this.parameter.accountNum)) return toast('请输入银行账号')
				if (!validateNumber(this.parameter.accountNum).valid) return toast('银行账号'+validateNumber(this.parameter
						.accountNum)
					.message)
				if (stringIsNull(this.parameter.accountName)) return toast('请输入银行开户行名称')
				// 核心代码：提取每个元素的url数组
				const logonList = this.logonList.map(item => item.url);
				const introductionList = this.introductionList.map(item => item.url);
				const businessLicenseList = this.businessLicenseList.map(item => item.url);
				const identityCardFront = this.identityCardFront.map(item => item.url);
				const identityCardReverseSide = this.identityCardReverseSide.map(item => item.url);
				this.parameter.logoImage = JSON.stringify(logonList)
				this.parameter.descImage = JSON.stringify(introductionList)
				this.parameter.licenceImage = JSON.stringify(businessLicenseList)
				this.parameter.legalFrontImage = JSON.stringify(identityCardFront)
				this.parameter.legalBackImage = JSON.stringify(identityCardReverseSide)
				console.log(JSON.stringify(this.parameter));
				var reqdata = {
					data: this.parameter
				}
				merchantAdd(reqdata).then(res => {
					if (res.code == 200) {
						toast(res.msg)
					} else {
						toast(res.msg)
					}
				})
			}







		}
	}
</script>

<style lang="scss">
	page {
		background-color: rgba(242, 242, 242, 1);
	}

	.merchant-management {
		margin: 15px;
		padding: 14px 15px;
		border-radius: 8px;
		background-color: #FFF;

		.merchant-column {
			margin-bottom: 16px;

			.merchant-info-name {
				color: black;
				font-size: 16px;
				font-weight: 600;
			}

			.red-line {
				width: 6px;
				height: 16px;
				margin-right: 8px;
				color: red;
				background-color: red;
				border-radius: 4px;
			}
		}

		.item-info {
			padding: 12px 0;

			.item-start {
				color: red;
			}

			.item-left {
				// width: 96px;
				margin-right: 14px;

				.left-text {
					color: black;
				}
			}

			.item-right {
				flex: 1;

				.rigit-text {
					color: #c9c9c9;
				}

				.arrow-icon {
					width: 6px;
					height: 12px;
					vertical-align: middle;
				}
			}

			.select-postion {
				padding: 4px 8px;
				font-size: 12px;
				color: royalblue;
				border-radius: 5px;
				border: 1px solid royalblue;
			}
		}

		.upload-management {
			margin-top: 12px;
		}

		.upload-item {
			display: flex;
			flex-direction: column;
			align-items: center;

			.upload-des {
				font-size: 12px;
				text-align: center;
				color: royalblue;
			}
		}
	}

	.submit {
		margin: 24px 20%;
		padding: 10px 15px;
		color: #FFF;
		font-size: 14px;
		font-weight: 500;
		text-align: center;
		border-radius: 8px;
		background-color: dodgerblue;
	}
</style>